package com.speechb.modules.shiro;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    private static Logger logger = LoggerFactory.getLogger(RedisKeyExpirationListener.class);

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对 redis 数据失效事件，进行数据处理
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = new String(message.getBody(), StandardCharsets.UTF_8);
        if (StringUtils.isEmpty(key)) {
            return;
        }
        String sessionKey = "";
        if (key.contains("$")) {
            String[] s = key.split("\\$");
            if (s.length > 1) {
                sessionKey = s[1];
            } else {
                sessionKey = s[0];
            }
            //cfd76d9f-7d70-4a57-8c65-1dd1d2999b2b
            //�� t $cfd76d9f-7d70-4a57-8c65-1dd1d2999b2b
        }
        if (MySessionManager.containsKey(sessionKey)) {
            MySessionManager.removeSession(sessionKey);
        }
    }
}